简体   繁体   中英

Deleting all lines that they have a specific characters between two positions in file in Linux

I want to create a script file to do these things:

  1. I'll give this script a file name and the script will delete all lines that have a specific character between two positions, for example: the script must delete all lines that have "mz" between 1st and 7th character only, otherwise will do nothing.
  2. Enhance this script to read the word and positions as an input from the user where the positions should be numbers, otherwise, the script should halt with an error message.

I've used

sed -i '/mz/d' filename 

but this command will delete all lines that have mz whatever the positions are. Thank you

Edit: Test.txt

1- hello guys,mz how are you? I hope you are doing fine.

2- I mz hope to do this thing correctly.

3- hi Mz, I hope to do this thing together.

this is a sample txt file that has 3 lines, first line will not be deleted because mz position isn't between 3th and 7th positions. the second line will be deleted because mz in the right positions. the third line will also deleted Note: I can use anythings, I'm not forced to use sed command

awk -v fst=$1 -v trm="$2" -v lst="$3" '{ astr=substr($0,fst,lst);if (match(astr,trm) ) { next } }1' filename

Using awk, pass the letter count as variable cnt set from the first passed script parameter. Set search term as variable trm set from the second passed parameter. Then create a variable astr which represents the first characters specified by cnt and utilising awk's substr function. Use this astr variable and attempt to match against the passed trm variable. If it matches, skip to the next line otherwise print with short hand 1.

mz在前 7 个位置时, mz前面最多有 5 个字符。

sed -ir '/^.{0,5}mz/d' file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM