2017-03-01 100 views
-1

我想用另一个范围替换文件中的数字范围。让说我有:替换文件中的数字范围

/dev/raw/raw16 
/dev/raw/raw17 
/dev/raw/raw18 

而且我要修改它们为:

/dev/raw/raw1 
/dev/raw/raw2 
/dev/raw/raw3 

我知道我可以使用awk或者sed它做,但就是无法将其正确写入。最简单的方法是什么?

回答

2

awk来救援!

$ awk -F'/dev/raw/raw' '{print FS (++c)}' ile 

/dev/raw/raw1 
/dev/raw/raw2 
/dev/raw/raw3 
+0

这是一种魅力。谢谢。 – JavaRed

0

我不会推荐更改设备名称。 无论如何,只是要替换字母或数字,你可以使用sed选项's'。

cat file.txt | sed s/raw16/raw1/g; > newfile.txt 

在此示例中,将所有raw16替换为raw1。 这里的一些其他的例子...

sed 's/foo/bar/'     # replaces in each row the first foo only 
sed 's/foo/bar/4'     # replaces in each row every 4. 
sed 's/foo/bar/g'     # replaces all foo with bar 
sed 's/\(.*\)foo/\1bar/'   # replace the last only per line 

+0

感谢您的意见。但我实际上正在寻找一个正则表达式来改变一个数字的范围,比如说raw [16-18]与raw [1-3] – JavaRed

0
# using /raw as field separator, so $2 is the end number in this case 
awk -v From=16 -v To=18 -v NewStart=1 -F '/raw' ' 
    # for lines where last number is in the scope 
    $2 >= From && $2 <=To { 
    # change last number to corresponding in new scope 
    sub(/[0-9]+$/, $2 - From + NewStart) 
    } 
    # print (default action of a non 0 value "filter") the line (modified or not) 
    7 
    ' file.txt \ 
> newfile.txt 

注:

  • 适应字段分隔符为你的真正需要
  • 套件为您的数据的样本,不若其他元素都行,但你可以很容易地适应这个代码foir您的目的