Skip to content
Advertisement

To add certain characters at the end of line when the line ends with “:”

I have a text file which contains two types of entries as below:

398/GHJKI:/opt/Check/D1/test_1234
875/GHgbhn:/opt/Check/D1/test_1235
398/ANgbhn:
398/ABNHJ:/opt/Check/D1/test_1237
123/ANgbhn:

I want to add NA at the end of line where “/opt/Check/D1/test_1237” does not exist, which means the line ends with “:”.

Please let me know how to do this.

I tried doing like this

if grep -q "test" "/home/C1.txt"; then
awk '$0=$0"NA"' /home/C1.txt > /home/C2.txt
else
:
fi

But this adds NA to each line..I want to add NA to line which ends with “:”

The output should look like:

398/GHJKI:/opt/Check/D1/test_1234
875/GHgbhn:/opt/Check/D1/test_1235
398/ANgbhn:NA
398/ABNHJ:/opt/Check/D1/test_1237
123/ANgbhn:NA

Advertisement

Answer

You may use this sed:

sed 's/:$/&NA/' file

398/GHJKI:/opt/Check/D1/test_1234
875/GHgbhn:/opt/Check/D1/test_1235
398/ANgbhn:NA
398/ABNHJ:/opt/Check/D1/test_1237
123/ANgbhn:NA

Here:

  • :$: Matches : before end of line
  • &NA: Replaces with original matched string i.e. : and NA
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement