K
K
ksvdon2014-12-01 00:04:06
bash
ksvdon, 2014-12-01 00:04:06

How to do substring replacement in bash?

Wrote a script to recalculate the time. I am reading a file in a loop. If the string starts according to the date/time pattern, I take this date/time and convert it to Unix time (seconds), add the desired difference in seconds, convert it back to the date/time format, and then replace the old value with the new one. But there's a problem. If there are several identical substrings in the text over time, then the replacement will take place not only in the substring processed in the loop, but everywhere, which ultimately affects the result ... How to process only a specific substring in the loop?

for myI in ./EX_FILE
    do
    co1=0
  while read line
        do
      case $line in
          ????-??-?????:??:*)
          line=`echo "$line" | awk '{print $1 " " $2}'`
          date_line_f[$co1]=$line
          line=`date --date="$line" +%s`
          let line=$line+$date_dif
          line=`date [email protected]$line +"%F %H:%M:%S"`
          date_line_s[$co1]=$line
          sed -i "s#${date_line_f[$co1]}#${date_line_s[$co1]}#" ./$myI - эта строка явно не годиться!!! Чем заменить перезапись старых данных но новые? Что бы замена шла не по всему тексту сразу, а конкретно в обрабатываемой подстроке!
      esac
        let co1=$co1+1
        done <./$myI
    done

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Evseev, 2014-12-01
@IlyaEvseev

More or less like this:

for f in "[email protected]" ; do
    while read a b; do
        case "$a" in
            ????-??-?????:??:*) a="$(date --date="$DATE_DIFF seconds $a" "+%F %H:%M:%S")" ;;
        esac
        echo $a $b
    done < "$f" > "$f.new"
    if diff -q "$f" "$f.new" >/dev/null
        then rm "$f.new"
        else mv "$f.new" "$f"
    fi
done

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question