簡體   English   中英

如何防止AWK中的Subshel​​l擴展

[英]How to prevent subshell expansion in awk

我有一個awk腳本,我需要在其中計算一些哈希值,這些哈希值出現在我正在處理的文件的第一個字段中。 我目前正在使用:

command="sha1sum "$1
command | getline hash

不幸的是,該命令在通過管道擴展到getline之前經歷了shell擴展。 對於其中包含空格或其他特殊字符的文件名,這是有問題的。 如何以允許使用任意字符的文件名的方式完成任務?

編輯:一些示例文件名可能包括foo(2).txtx&y.mp3

我也將在這里包括整個程序,因為它不會太長。 目的是從文本文件中獲取文件名列表並搜索重復的文件。

#take a list of filenames and compute sha1sums to look for duplicates
BEGIN {storage[0]=0}
{
    command="sha1sum "$1
    command | getline hash
    split(hash, line)
    #storage array has the sha1sum hash as a key and the filename as a value
    #check each hash in storage, and report the duplicate if the current
    #sum matches any encountered before
    hash_exists=0
    for (x in storage) {
        if (x == line[1]) {
            hash_exists=1
            print("Duplicate found: " line[2])
        }
    }

    if (hash_exists == 0) {
        storage[line[1]]=line[2]
    }

    close(command)
}
$ ll file\ with\ spaces
-rw-rw-r-- 1 foo foo 0 Mar  5 16:49 file with spaces

$ echo "file with spaces" | awk -F: '{
    command="sha1sum \"" $1 "\"";
    command | getline line
    print line
}'
da39a3ee5e6b4b0d3255bfef95601890afd80709  file with spaces

sha1sum前綴為set -f;

$ touch f\*
$ nawk 'BEGIN {
  command="set -f;sha1sum f*"
  command | getline hash
  print hash
}'
da39a3ee5e6b4b0d3255bfef95601890afd80709  f*

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM