0

我在 while 循环中使用 grep 命令时遇到问题。下面是我的代码:

#!/bin/bash
#FILE:  grep_track
#will read in a list of track IDs and grep the track data from the original track files
set=-x

track_list=Top95_HSI_forGrep.txt
track_path="/mnt/gpfs/backup/jpty_surge/kimberly/Launch_multiple_storms/input/$track_list"
outname=$track_list

#echo track_list $track_list
#echo track_path $track_path
#echo outname $outname

IFS=$","
while read trackid fileid 
do
   file="input/track_param_$fileid"
   outfile="output/$outname"
   echo fileid $fileid
   echo trackid $trackid
   echo file $file
   echo outfile $outfile
   grep $trackid $file > $outfile 
done < $track_path

一切似乎都在正确读取(根据我的回声响应),但是我收到以下错误:

: No such file or directory1.txt

谁能帮我弄清楚发生了什么?谢谢!

4

1 回答 1

1

引用你的论点grep

grep "${trackid}" "${file}" >> "${outfile}"

这样,如果其中一个$trackid$file包含空格,它将被视为一个参数grep而不是多个参数。请注意,>> 附加到文件“ ${outfile}”(而不是>,它会截断)。


\r要从输入文件中删除错误的 s,请使用tr(1)

tr -d '\r' < "${track_path}" | while read trackid fileid 
# [...]
done

我还建议进行一些健全性检查,例如:

if [[ -f "${file}" ]] ; then
    grep "${trackid}" "${file}" > "${outfile}"
else
    echo "Could not find file [${file}]. Skipping."
fi

所以你完成的脚本可能如下所示:

#!/bin/bash
#set -x

track_list=Top95_HSI_forGrep.txt
track_path="${1-/mnt/gpfs/backup/jpty_surge/kimberly/Launch_multiple_storms/input}/${track_list}"
outname="${track_list}"
output_directory="output"
outfile="${output_directory}/${outname}"

if [[ ! -f "${track_path}" ]]; then
    echo "Could not find track_path input [${track_path}]. Exiting"
    exit
fi

if [[ ! -d "${output_directory}" ]] ; then
    echo "Creating output directory [${output_directory}]..."
    mkdir -p "${output_directory}"
fi

IFS=$","
tr -d '\r' < "${track_path}" | while read trackid fileid
do
    file="input/track_param_${fileid}"
    if [[ -f "${file}" ]]; then
        grep "${trackid}" "${file}" >> "${outfile}"
    else
        echo "Could not find file [${file}]. Skipping."
    fi
done
于 2013-02-07T02:15:57.853 回答