开发者

sed remove line containing a string and nothing but; automation using for loop

Q1: Sed specify the whole line and if the line is nothing but the string then delete


I have a file that contains several of the following numb开发者_运维问答ers:

1 1
3 1
12 1
1 12
25 24
23 24

I want to delete numbers that are the same in each line. For that I have either been using: sed '/1 1/d' < old.file > new.file OR sed -n '/1 1/!p' < old.file > new.file

Here is the main problem. If I search for pattern '1 1' that means I get rid of '1 12' as well. So for I want the pattern to specify the whole line and if it does, to delete it.

Q2: Automation of question 1


I am also trying to automate this problem. The range of numbers in the first column and the second column could be from 1 to 25.

So far this is what I got:

for ((i=1;i<26;i++)); do
 sed "/'$i' '$i'/d" < oldfile > newfile; mv newfile oldfile;
done

This does nothing to the oldfile in the end. :(


This would be more readable with awk:

awk '$1 == $2 {next} {print}' oldfile > newfile

Update based on comment:

If the requirement is to remove lines where the two values are within 1 of each other:

awk '{d = $1-$2; if (-1 <= d && d <= 1) next; else print}' oldfile

Unfortunately, awk does not have abs() (at least nawk and gawk don't)


Just put the first number in a group (\([0-9]*\)) and then look for it with a backreference (\1). Since the line to delete should contain only the group, repeated, use the ^ to mark the beginning of line and the $ to mark the end of line. For example, for the following file:

$ cat input 
1 1
3 1
12 1
1 12
12 12
12 13
13 13
25 24
23 24

...the result is:

$ sed '/^\([0-9]*\) \1$/d' input 
3 1
12 1
1 12
12 13
25 24
23 24


You can also do it with grep:
grep -E -v "([0-9])*\s\1" testfile

Look for multiple digits in a row and remember them, followed by a single whitespace, followed by whatever digits you remembered.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜