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
ship
becomesp
? Include that case in your example and if your "string" can contain regexp metachars then include those test cases too. See how-do-i-find-the-text-that-matches-a-pattern. Oh and also state/show if your string can contain backslashes as that impacts potential solutions. – Ed Morton Apr 30 '21 at 16:56