简体   繁体   中英

Shell script to extract a filename from log message lines

I have txt file which listed with some line. Each line has image names included. What I want is, The shell script that edit same txt file OR copy particular image name to new file.

This is my txt file having list of images with their paths. 在此处输入图片说明

And I want output like this:

在此处输入图片说明

I want only image names should be extract from those lines.

Using gnu sed you can do:

sed -r 's~^[^[:blank:]]*/([^/ ]+) .*$~\1~' file
1.png
1@2x.png
2.png
2@2x.png
3.png

您可以使用此awk

awk '{ split($1,arr,"/"); print arr[length(arr)] }' yourfile > output.txt

You can do something like:

cat the_file.txt|while read file; do
    echo $(basename $file)
done

And (if needed) redirect the output on another file.

while read fn rest
do
    basename "$fn"
done < file.txt

This will read your input line by line. It will put the filename (including path) into the fn variable, and whatever is on the rest of the line into rest . Then it uses the basename command to strip off the path and just print out the filename itself.

This is another sed solution that doesn't use extended regular expression (more portable solution):

sed 's/^.*\/\([^[:blank:]\/]*\)[[:blank:]].*$/\1/' sourceFile > destFile

You have to replace sourceFile and destFile white the path to oridinal and destination file respectively.

The command look for any string without blank char or slashes \\([^[:blank:]\\/]*\\) preceeded by a slash ^.*\\/ and followed by a blank char [[:blank:]].*$ than the patter is substitituded with the first matching string /\\1/ .

You could read a quick sed reference here .

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