Home > Net >  sed or awk replace match with first five characters
sed or awk replace match with first five characters

Time:08-10

I have to replace the word pünktlich with the time(first five characters) at the beginning of each line. It's not always 14:03. The time could change but keeps the same format.

Having:

14:03,RB 87(57140),Donauwörth,pünktlich,Kein Grund

Needed:

14:03,RB 87(57140),Donauwörth,14:03,Kein Grund

The time stands always at the beginning of each line.

Do you have any idea?

CodePudding user response:

Using GNU sed's capturing groups, let file.txt content be

14:03,RB 87(57140),Donauwörth,pünktlich,Kein Grund

then

sed 's/^\([^,]*\)\(.*\)pünktlich/\1\2\1/' file.txt

gives output

14:03,RB 87(57140),Donauwörth,14:03,Kein Grund

Explanation: I use 2 capturing groups: 1st is from beginning of line (^) to first , i.e. it does contain zero or more (*) not (^) commas (,), 2nd is everything between 1st group and pünktlich. I replace what was matched by content of 1st group, content of 2nd group, content of 1st group again. Disclaimer: if any line contains more than one pünktlich then only last one will be changed to time.

(tested in GNU sed 4.2.2)

CodePudding user response:

You can do this simply using awk. let's say your file is named test.csv:

awk 'BEGIN{FS=","; OFS=","}{print $1,$2,$3,$1,$5}' test.csv

Output is:

14:03,RB 87(57140),Donauwörth,14:03,Kein Grund

Explanation: You define input field seperator with FS and output field separator with OFS. Then you set the columns in the order you want. $1 means the first column, $2 means the second column and this is the same for other columns.

  • Related