简体   繁体   中英

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. I want to figure out how to remove all characters before last 7 characters of each line. I figured this is possible using the sed command and did research on google and the sed man page. 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 's/.\{n\}$//'

I'm fairly new to bash and can't find effective resources to find out how to format the sed command. Does anyone know how to alter this command to print only last 7 characters of each line .

If name of the files are like file1, file2, file3......filen then use

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. it makes changes in the input files.

Without sed , you could use cut :

cut -c -7 file

or with awk :

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

Use this Perl one-liner, which utilizes 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 :

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. Eg, for 6 characters it only prints 6, and for an empty string input it prints empty string.

The Perl one-liner uses these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-p : Loop over the input one line at a time, assigning it to $_ by default. Add print $_ after each loop iteration.
-l : Strip the input line separator ( "\\n" on *NIX by default) before executing the code in-line, and append it when printing.

Using sed to extract last n characters of each line:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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