• Uncategorized

About linux : need-to-insert-a-word-to-a-specific-line-at-the-end-in-a-file-from-a-remote-ssh

Question Detail

i have a file like below

cat test -(X- different words )
XXXXXXXXXXXXXXXXXXX
always-a-constant:::pete
XXXXXXXXXXXXXXXXX

i need to add steve next to pete and generate a new file and the output should look like the below.

    XXXXXXXXXXXXXXXXXXX
    always-a-constant:::pete,steve
    XXXXXXXXXXXXXXXXX

I can use awk

cat  test | grep -i alw|  awk '{print $0",steve"}' 
always-a-constant:::pete,steve

but i still need the other lines XXX .

Question Answer

Method 1: sed

With this as our test file:

$ cat test
XXXXXXXXXXXXXXXXXXX
always-a-constant:::pete
XXXXXXXXXXXXXXXXX

We can add ,steve after any line that starts with alw with:

$ sed '/^alw/ s/$/,steve/' test
XXXXXXXXXXXXXXXXXXX
always-a-constant:::pete,steve
XXXXXXXXXXXXXXXXX

In sed’s regular expressions, $ matches at the end of a line. Thus, s/$/,steve/ adds ,steve on at the end of the line.

Method 2: awk

$ awk '/^alw/ {$0=$0",steve"} 1' test
XXXXXXXXXXXXXXXXXXX
always-a-constant:::pete,steve
XXXXXXXXXXXXXXXXX

In awk, $0 represents the current line. $0",steve" represents the current line followed by the string .steve. Thus, $0=$0",steve" replaces the current line with the current line followed by ,steve.

The final 1 in the awk command is important: it is awk’s shorthand for print-the-line. Any non-zero number would work. In more detail, awk treats the 1 as a condition (a boolean). Because it evaluates to true (nonzero), the action is performed. Since we didn’t actually specify an action, awk performs the default action which is to print the line. Hence, 1 is shorthand for print-the-line.

Method 3: sed

Alternatively, we can add ,steve after any line that ends with :::pete with:

$ sed 's/:::pete/&,steve/' test
XXXXXXXXXXXXXXXXXXX
always-a-constant:::pete,steve
XXXXXXXXXXXXXXXXX

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.