as tittle,如何执行“大于”删除特定行? 我有一个这样的文件:
bash-4.2$ cat testfile.txt
string1 1 1
AAA 2 2
string2 2 2
BBB 3 3
string3 3 3
string4 4 4
string5 5 5
string6 6 6
CCC 6 6
string7 7 7
string8 8 8
string9 9 9
string10 10 10
DDD 11 11
string11 11 11
string12 12 12
string13 13 13
我想删除一些包含“string [[:digit:]]”的行,但是需要string1到字符串“$ num”,num由变量定义。例如,我想保留那些包含string1-5并删除string6-string99的行,我试过了:
#!/bin/bash
read -p "Please Assign the Number of String Line that You Wanna Keep: " num
cat testfile.txt | sed -e "/string[`expr $num + 1`-9]/d" > new_testfile.txt
但它只在0-8范围内工作,有没有办法用sed或awk执行它?
答案 0 :(得分:3)
这个'awk`应该这样做:
awk '/^string/ {n=substr($1,7)+0;if (n>5 && n<100) next}1' file
string1 1 1
AAA 2 2
string2 2 2
BBB 3 3
string3 3 3
string4 4 4
string5 5 5
CCC 6 6
DDD 11 11
它只是跳过string"x"
的任何一行,其中x
大于5
且小于100
如果高/低来自变量,则应执行以下操作:
high=99
low=6
awk '/^string/ {n=substr($1,7)+0;if (n>=l && n<=h) next}1' h="$high" l="$low" file
string1 1 1
AAA 2 2
string2 2 2
BBB 3 3
string3 3 3
string4 4 4
string5 5 5
CCC 6 6
DDD 11 11
答案 1 :(得分:1)
以下是awk
的一种方式:
$ read -p "Please Assign the Number of String Line that You Wanna Keep: " num
Please Assign the Number of String Line that You Wanna Keep: 5
$ awk -v max="$num" '/string/{line=$0;sub(/string/,"",$1);if($1+0<=max){print line};next}1' file
string1 1 1
AAA 2 2
string2 2 2
BBB 3 3
string3 3 3
string4 4 4
string5 5 5
CCC 6 6
DDD 11 11