简体   繁体   English

使用 bash 打印每行的最后 n 个字符

[英]Print the last n characters of each line using bash

I have a list of files, with each file contained on its own line.我有一个文件列表,每个文件都包含在自己的行中。 Each filename has a variable length of n but the last 7 characters of each file are specific identifiers.每个文件名的长度为n ,但每个文件的最后 7 个字符是特定标识符。 I want to figure out how to remove all characters before last 7 characters of each line.我想弄清楚如何删除每行最后 7 个字符之前的所有字符。 I figured this is possible using the sed command and did research on google and the sed man page.我认为使用 sed 命令可以做到这一点,并对谷歌和 sed 手册页进行了研究。 However, I've only found resources that show how to format sed to remove the last n characters in each line, which is done as so:但是,我只找到了显示如何格式化 sed 以删除每行中的最后n字符的资源,这样做是这样的:

sed 's/.\{n\}$//'

I'm fairly new to bash and can't find effective resources to find out how to format the sed command.我对 bash 还很陌生,找不到有效的资源来了解如何格式化 sed 命令。 Does anyone know how to alter this command to print only last 7 characters of each line .有谁知道如何更改此命令以仅打印每行的最后 7 个字符

If name of the files are like file1, file2, file3......filen then use如果文件名像 file1, file2, file3......filen 那么使用

sed -i 's,.*\(.\{7\}\)$,\1,' file*

or或者

for i in file*; do
   sed -i 's,.*\(.\{7\}\)$,\1,' $i
done

but be careful when use -i.但使用-i 时要小心。 it makes changes in the input files.它在输入文件中进行更改。

Without sed , you could use cut :没有sed ,你可以使用cut

cut -c -7 file

or with awk :或使用awk

awk '{print (substr($0,length($0)-7+1))}' file

Use this Perl one-liner, which utilizes substr .使用这个 Perl one-liner,它利用了substr
First, create input for testing:首先,创建用于测试的输入:

cat > in_file <<EOF
foo_bar_1234567
1234567

123456
EOF

Print the last 7 characters in each string of the in_file :打印in_file每个字符串中的最后 7 个字符:

perl -lpe '$_ = substr $_, -7;' in_file > out_file

Output:输出:

1234567
1234567

123456

Note that if the input has less than 7 characters, it prints only the available number of characters.请注意,如果输入少于 7 个字符,它只会打印可用的字符数。 Eg, for 6 characters it only prints 6, and for an empty string input it prints empty string.例如,对于 6 个字符,它只打印 6,对于空字符串输入,它打印空字符串。

The Perl one-liner uses these command line flags: Perl 单行使用这些命令行标志:
-e : Tells Perl to look for code in-line, instead of in a file. -e :告诉 Perl 查找内嵌代码,而不是在文件中。
-p : Loop over the input one line at a time, assigning it to $_ by default. -p :一次循环输入一行,默认情况下将其分配给$_ Add print $_ after each loop iteration.在每次循环迭代后添加print $_
-l : Strip the input line separator ( "\\n" on *NIX by default) before executing the code in-line, and append it when printing. -l :在执行内联代码之前去除输入行分隔符(默认情况下 *NIX 上的"\\n" ),并在打印时附加它。

Using sed to extract last n characters of each line:使用 sed 提取每行的最后 n 个字符:

sed -n 's/.*\(.\{n\}$\)/\1/p'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM