qdread
qdread

Reputation: 3943

Append text to first line not containing a pattern?

I want to use a Unix command such as sed or awk to append the string "#DONE" to the end of the first line in a text file not already containing the string "#DONE".

For example the input file would be something like

qsub job1.sh #DONE
qsub job2.sh #DONE
qsub job3.sh 
qsub job4.sh 

and the desired output would be

qsub job1.sh #DONE
qsub job2.sh #DONE
qsub job3.sh #DONE
qsub job4.sh 

I am not experienced with this type of scripting, and I've searched but can't find the exact solution for this on SO.

Upvotes: 1

Views: 68

Answers (4)

karakfa
karakfa

Reputation: 67467

another awk

awk -v k="#DONE" '$NF!=k && !c++{$++NF=k}1' file

!c++ will ensure it will be done only once, $++NF=k increments the number of fields and sets the last field to the value.

Upvotes: 2

potong
potong

Reputation: 58351

This might work for you (GNU sed):

sed '/#DONE$/!{s/$/#DONE/;:a;n;ba}' file

Append #DONE to first line that does not have it, then print the remainder of the file.

Upvotes: 2

Ivonet
Ivonet

Reputation: 2731

pipe aproach where file is your file (place twice)

grep -nrv -m1 "#DONE" "file" | awk -F  ":" '{print $2}' | xargs -I {}  awk 'FNR=={},FNR=={}{$3="#DONE"};1' "$1" >tmp && mv tmp "file"

This will work as long as you are not completely #DONE.

If that happends the file will be emptied :-)

haven't figured that one out yet

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Awk approach:

awk '!f && !/#DONE$/{ $0=$0 "#DONE"; f=1 }1' file

The output:

qsub job1.sh #DONE
qsub job2.sh #DONE
qsub job3.sh #DONE
qsub job4.sh

Upvotes: 3

Related Questions