bash 如何读取特定行和特定位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/11607757/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read specific line and specific position?
提问by faizal
I have a problem reading a string in specific line and specific position. I have an input file that has a fixed position and fixed length for each value in every row. This is an example of my input file:
我在读取特定行和特定位置的字符串时遇到问题。我有一个输入文件,每行中的每个值都有一个固定的位置和固定的长度。这是我的输入文件的示例:
sltele     Hoodie   24051988 d12Hdq
sltele     Hoodie   07051987 d30Hdq
sltele     Hoodie   07082011 d08Hdq
sltele     Hoodie   09081961 d04Hdq
sltele     Hoodie   20041962 d14Hdq
sltele     Hoodie   20032000 d01Hdq
sltele     Hoodie   13062002 d05Hdq
I need to read a string in 3rd column in first line. So, I used this
我需要在第一行的第三列中读取一个字符串。所以,我用了这个
awk 'NR==1 {print , }' inputfile.inp
How can I get an exact result with character position as parameter? (12nd-18th and 21st-28th)
如何以字符位置为参数获得准确结果?(12-18 日和 21-28 日)
回答by Vijay
use cut -c
用 cut -c
Check the man page for more details.
查看手册页以获取更多详细信息。
also you can use the below:
您也可以使用以下内容:
echo "abcdefghij" | awk '{print substr(awk 'NR==1 {print substr(sed -rn "1 s@.{11}(.{7}).{2}(.{8})@@p" filename
,12,6),substr(##代码##,21,7)}' inputfile.inp
,2,2),substr(##代码##,6,2)}'
bc fg
above is 2 characters from second position and 2 chars from 6th position.
上面是第二个位置的 2 个字符和第六个位置的 2 个字符。
your solution will be :
您的解决方案将是:
##代码##the above command will get the 6 chars from 12th position and 7 chars from 21st position in line number 1.
上面的命令将从第 1 行的第 12 个位置获取 6 个字符,从第 21 个位置获取 7 个字符。
回答by uzsolt
You can use sedtoo:
您也可以使用sed:
##代码##Explanation:
解释:
- -ndon't print the lines
 - sreplace
 - 1only the first line
 - .{11}omit 11 characters
 - (.{7})save 7 characters (char 12-18)
 - .{2}omit 2 chars (19-20)
 - (.{8})save 8 chars (21-28)
 - \1\2replace the string with the first and second saves
 - pprint the line specified line
 
- -n不打印行
 - s替换
 - 1只有第一行
 - .{11}省略 11 个字符
 - (.{7})保存 7 个字符(字符 12-18)
 - .{2}省略 2 个字符 (19-20)
 - (.{8})保存 8 个字符 (21-28)
 - \1\2用第一次和第二次保存替换字符串
 - p打印指定行的行
 

