[英]Printing 3 character of each line in a file in bash shell
I was solving one problem from one site, question is as follows: 我正在从一个站点解决一个问题,问题如下:
"Given N lines of input in a file, print the 3rd character from each line as a new line of output. It is guaranteed that each of the n lines of input will have a 3rd character." “给定文件中的N行输入,将每行的第3个字符打印为新的输出行。确保n行输入中的每行将具有第3个字符。”
So to solve the problem I have written a command 所以为了解决这个问题,我写了一个命令
while read -r line
do
echo ${line:2:1}
done < sample.txt
Content in "sample.txt" is : “ sample.txt”中的内容是:
C.B - Cantonment Board/Cantonment
C.M.C – City Municipal Council
C.T – Census Town
E.O – Estate Office
G.P - Gram Panchayat
I.N.A – Industrial Notified Area
I.T.S - Industrial Township
M – Municipality
M.B – Municipal Board
M.C – Municipal Committee
I am getting output as follows: 我得到的输出如下:
B
M
T
O
P
N
T
â
B
C
According to the site, the answer should be: 根据站点,答案应该是:
B
M
T
O
P
N
T
в
B
C
Please not that 3rd last output is "в" and I am getting "â" I am new to the ascii, uts-8 conversion so not aware if this has any relation . 请不要倒数第三个输出是“в”,而我却得到“â”,我是ascii,uts-8转换的新手,所以不知道这是否有任何关系。
What should be change in the code to bring this answer? 带来此答案的代码应进行哪些更改?
这可以通过简单的cut
调用来完成:
$ cut -c3 sample.txt
使用awk
:使用FS=""
列更改为字符
awk -vFS="" '{print $3}' file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.