Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a letter with another from the last word from the last two lines of a text file

Tags:

sed

awk

How could I possibly replace a character with another, selecting the last word from the last two lines of a text file in shell, using only a single command? In my case, replacing every occurrence of a with E from the last word only.

Like, from a text file containing this:

tree;apple;another
mango.banana.half
monkey.shelf.karma

to this:

tree;apple;another
mango.banana.hElf
monkey.shelf.kErmE

I tried using sed -n 'tail -2 'mytext.txt' -r 's/[a]+/E/*$//' but it doesn't work (my error: sed expression #1, char 10: unknown option to 's).

like image 946
Marcus-Silviu Ilisie Avatar asked Oct 15 '20 07:10

Marcus-Silviu Ilisie


People also ask

How do I remove the last word from a text file in Python?

You can just open the txt file into a string and then remove the last word from the string by changing the string into a list. Then you can remove the last element from the list and turn it back into a string with a for loop to attach all list elements back into one string variable.

How do I remove the last word in Notepad ++?

If your goal is to surround the last word in a line with slashes, you can accomplish this task very easily by using regular expressions: In your Notepad++ window press Ctrl + F , choose the tab titled 'Replace' and select 'Regular Expression' search mode.


2 Answers

Could you please try following, tac + awk solution. Completely based on OP's samples only.

tac Input_file | 
awk 'FNR<=2{if(/;/){FS=OFS=";"};if(/\./){FS=OFS="."};gsub(/a/,"E",$NF)} 1' | 
tac

Output with shown samples is:

tree;apple;another
mango.banana.hElf
monkey.shelf.kErmE

NOTE: Change gsub to sub in case you want to substitute only very first occurrence of character a in last field.

like image 197
RavinderSingh13 Avatar answered Nov 14 '22 01:11

RavinderSingh13


This might work for you (GNU sed):

sed -E 'N;${:a;s/a([^a.]*)$/E\1/mg;ta};P;D' file

Open a two line window throughout the length of the file by using the N to append the next line to the previous and the P and D commands to print then delete the first of these. Thus at the end of the file, signified by the $ address the last two lines will be present in the pattern space.

Using the m multiline flag on the substitution command, as well as the g global flag and a loop between :a and ta, replace any a in the last word (delimited by .) by an E.

Thus the first pass of the substitution command will replace the a in half and the last a in karma. The next pass will match nothing in the penultimate line and replace the a in karmE. The third pass will match nothing and thus the ta command will fail and the last two lines will printed with the required changes.

like image 20
potong Avatar answered Nov 14 '22 02:11

potong