Add text at the end of line conditionally

Hi All,

I have a file as below:

cat myfile

abcdef
NA
rwer
tyujkl
na

I wish to add the text ".txt" at the end of all lines except the lines starting with NA or na.

I know i can add text at the end of line using following command but I am not sure how to valiate the condition.

sed 's/$/\.txt/g' myfile >temp
mv temp myfile

Can any one help me on how to achieve this? Your help is highly appreciated.

Regards
Angshuman

try

awk '{print ($0~/^NA|na/?$0:$0".txt")}' urfile
1 Like
awk '/^na|^NA/||$0=$0".txt"' file
1 Like
sed '/^[Nn][Aa]$/{p;d;};s/.*/&.txt/' infile
1 Like
sed '/^[Nn][Aa]/!s/$/.txt/' file
1 Like

@Scruti,
lol yes, it's better :smiley:

what is suppposed to happen if the file contain a line like

Na, i am not a line like the others !

??

1 Like
 $  ruby -ne 'chomp; print ($_ !~ /^\s*(NA|na)\s*$/i ) ? $_+".txt\n": $_+"\n" ' file 
1 Like

won't work if there are strings like "nap", "NAG" etc.

1 Like

try:

awk '{print (($0=="NA" || $0=="na")?$0:$0".txt")}'  urfile
1 Like

Hi All,

Thank you all for the reply. I was basically flooded with optins and was bit confused which one to use. However, I have used the option given by Scrutinizer as I could comprehend it clearly. However, took note of all the commands which I can definitely use in future.

Once again thank you all for your help.

Regards
Angshuman

note that you will have to add something to the regex to his solution make it match NA or na exactly as well.

I do not see why that would be necessary. From post #1:

Hi Scrutinizer,

I did not understand your question completely. Which one are you referring to? The file might have lines containinig only NA or na. I do not need to add anything at the end of these lines. Because, there will be no files with the naem NA.txt or na.txt

Hence I need to exclude those lines. Was your question for this?

Regards
Angshuman

Hi angshuman, I was responding to ghostdog74's remark..

He had said "I wish to add the text ".txt" at the end of all lines except the lines starting with NA or na." while referring to his example. Although there are no examples of "nagging" or "NATIONAL" etc, instinctively, one would want to avoid matching words that start with NA or na and is part of a bigger word. Of course, if OP has not problem with that, then that's fine.