簡體   English   中英

為什么我的“echo”只顯示 1 個字? (Linux-Bash)

[英]Why does my "echo" only display 1 word? (Linux-Bash)

我有一個 username.txt 顯示用戶名和組,用“,”分隔。 我試圖僅將“訪客”組中的用戶名復制到新的 txt。

我的用戶名.txt:

mark,staff
jason,visitor
jack,visitor
orlando,visitor

這是我當前的 bash 腳本:

#!/bin/bash

username=username.txt

while IFS=, read username1 group1; do
 if [ $group1 = "visitor" ]; then
   echo $username1 > reportvisitors.txt
 fi
done < $username

我的報告訪問者.txt

預期輸出:

jason
jack
orlando

實際輸出:

jack

您正在使用>而不是>>並且它會在循環的每次迭代期間覆蓋該文件中當前的數據。 要將文本附加到文件中,您需要改用>> 只需像這樣修改您的腳本:

#!/bin/bash
username=username.txt

while IFS=, read username1 group1; do
echo $username1 $group1
 if [[ $group1 == "visitor" ]]; then
   echo $username1 >> reportvisitors.txt
 fi
done < $username

如果此腳本的唯一目的是收集訪問者,則可以在awk one liner 中實現相同的結果,如下所示:

awk -F, '{if($2 == "visitor")print $1}' username.txt > reportvisitors.txt

將 io 重定向運算符移動到循環的末尾。

#!/bin/bash

username=username.txt

while IFS=, read username1 group1; do
 if [ "$group1" = "visitor" ]; then
   echo "$username1"
 fi
done < "$username" > reportvisitors.txt

首先創建一個臨時文件來打印結果。 您可以使用mktemp實用程序來做到這一點。 然后,如果沒有發生錯誤,則將該文件移動到reportvisitors.txt 使用>>而不是>附加到臨時文件:

#!/bin/bash

username=username.txt
tmpfile=$(mktemp)

while IFS=, read username1 group1; do
    if [ $group1 = "visitor" ]; then
        echo $username1 >> "$tmpfile"
    fi
done < $username

mv "$tmpfile" reportvisitors.txt

這避免了即使腳本因錯誤而失敗也會丟失reportvisitors.txt的先前內容的問題。

理想情況下,您的腳本應該具有錯誤處理功能,並在出現錯誤時刪除臨時文件。

暫無
暫無

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

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