开发者

AWK working with variables, not files

I read this post, but I cannot figure out how to make what I need. I have a variable, which is a path, so I would like to have the name of the file (last column if I separate by /).

So I tried several combinations, such as:

#!/bin/sh

source=$1
target=$2


for i in "$source"/*
do
    $name = awk -F/ -v '{ prin开发者_运维百科t $NF }' $i
    echo $name
done

But no success, could anybody help me?? Thanks in advance


A bit unclear... You would like to extract the filename from a path?

to get path without file-name use dirname:

$ dirname /usr/bin/foo.bar
/usr/bin

to get file-name without path use basename

$ basename /usr/bin/foo.bar
foo.bar

Using awk:

$ echo $a 
/usr/bin/foo.bar  

$ echo $a | awk -F/ '{print $NF}' 
foo.bar


you can just use the shell to extract the file names without external tools

for file in $source/*
do
  echo ${file##*/}
done


If you want to extract the file name, then use basename as Fredrik suggested. Here is a solution:

#!/bin/sh

source=$1
target=$2

for i in "$source"/*
do
    name=$(basename $i)
    echo $name
done

This solution works, but it has a bug: if either a directory or file contains space in its name, then it does not work correctly. Here is my revised solution:

#!/bin/sh

source=$1
target=$2

pushd "$source" >/dev/null 2>&1
for name in *
do
    echo $name
done
popd >/dev/null 2>&1

Note that I use pushd/popd to get into and out of the source directory. Since I am already in the source directory, I don't need to call basename.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜