Pregunta

I have a text file that has a white space separated values. Column 9th has field that needs to be matched(ice), but column 11th needs substitution based on the match. Example :

    a b c d e f g h ice j k l m

Intended output :

    a b c d e f g h ice j keep l m

I'm trying use this :

    sed -i -r 's/ice [^ ]*/ice keep/' test.log

But it give this :

    a b c d e f g h ice keep k l m

Please help me. I'm not familiar with sed and regex.

¿Fue útil?

Solución

This is more suitable for awk or any other tool that understands columns:

awk '{if ($9=="ice") {$11="keep"} print}' inputfile

Fields in awk are delimited by space by default. $9 would denote the 9th field. If the 9th field is ice, change the 11th to keep.

For your input, it'd produce:

a b c d e f g h ice j keep l m

You could do it using sed too, but it's not quite straight-forward:

sed -r 's/^(([^ ]+ ){8}ice \S+ )(\S+)/\1keep/' inputfile

Here ([^ ]+ ){8} would match the first 8 fields. (([^ ]+ ){8}ice \S+ ) matches 10 fields with the 9th being ice and captures it into a group that is substituted later making use of a backreference, \1.

Otros consejos

This might work for you (GNU sed):

sed -r '/^((\S+\s+){8}ice\s+\S+\s)\S+/s//\1keep/' file

This matches the 9th non-spaced value to ice and then changes the 11th non-spaced value to keep.

in your sample it work but it does not take count of column number, do you realy need the column reference or just the content ?

sed '/ice/ s/k/keep/' YourFile
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top