0

I want to remove a string which is coming from a variable in a line. remove_text=' hi';

File:

kjdkjdkjddkjd
djdk hi sjjsj
jfjf sisj hi
jdkjdk dkjdkdjd hi
hi sksk

I want to to delete hi from Nthline ( 2nd line in this case.)

File:

kjdkjdkjddkjd
djdk sjjsj
jfjf sisj hi
jdkjdk dkjdkdjd hi
hi sksk
αғsнιη
  • 41,407

2 Answers2

1

It is simple with sed.

sed '2s/hi//' filename

where 2s substitutes on line 2, hi (the pattern in the first pair of slashes) is the pattern to be replaced, and there is nothing between the second pair of slashes causing the pattern to be deleted.

This command works with variables as well but you have to be careful to enclose the command in double quotes instead of single quotes, as follows

remove_text=' hi'
sed "2s/${remove_text}//" filename

In case you want to select your line number through a variable, you can do that as well.

ln=2
remove_text=' hi'
sed "${ln}s/${remove_text}//" filename

Using the option -i with sed will cause in-place substitution, or update the file.

unxnut
  • 6,008
  • 1
    and to mention that in that case ${remove_text} will be treated as regex and will cause sed fail if there has a slash / character in it or single/double quote or maybe other characters too, IDK – αғsнιη Apr 30 '21 at 13:45
  • see also https://unix.stackexchange.com/a/129063/72456 – αғsнιη Apr 30 '21 at 13:51
0

Using any awk:

remove_text=' hi';

awk -v rmtxt="$remove_text" ' NR==2{ len=length(rmtxt); ind=index($0, rmtxt); print substr($0, 1, ind-1) substr($0, ind+len) }1' infile

or alternatively using the match() function (match() treats second arg as regex):

awk -v rmpat="$remove_text" '
NR==2{ match($0, rmpat);
       print substr($0, 1, RSTART-1) substr($0, RSTART+RLENGTH)
}1' infile

particularly this is to find the first occurrences position of the "remove_text" in the second line of input and print two substrings, one before and another after that.


if you want to remove all occurrences of that "remove_text", do it as following:

awk -v rmtxt="$remove_text" 'BEGIN { FS=rmtxt; OFS="" } NR==2{ $1=$1 }1' infile

that is defining the "remove_text" as the awk's field separator and on the second line of input re-evaluate the input line based on FS/OFS and print the final changes with 1 used.

alternatively, using gsub() function, but note that using gsub() will treat the "remove_text" value as the regex not a literal strings as above solutions does based on string match:

awk -v rmpat="$remove_text" 'NR==2{ gsub(rmpat, "") }1' infile
αғsнιη
  • 41,407