我有一個格式如下的txt檔案:
test1
test2
test3
如何使用 bash 將其轉換為這樣的格式?
test1,test2,test3
uj5u.com熱心網友回復:
假設“使用 Bash”意味著“沒有任何外部行程”:
if IFS= read -r line; then
printf '%s' "$line"
while IFS= read -r line; do
printf ',%s' "$line"
done
echo
fi
uj5u.com熱心網友回復:
舊答案在這里
特爾;博士:
cat "export.txt" | paste -sd ","
uj5u.com熱心網友回復:
另一個bash避免顯式回圈的純實作:
#!/usr/bin/env bash
file2csv() {
local -a lines
readarray -t lines <"$1"
local IFS=,
printf "%s\n" "${lines[*]}"
}
file2csv input.txt
uj5u.com熱心網友回復:
如果您不想要終止換行符:
$ awk '{printf "%s%s", sep, $0; sep=","}' file
test1,test2,test3
或者如果你這樣做:
awk '{printf "%s%s", sep, $0; sep=","} END{print ""}' file
test1,test2,test3
uj5u.com熱心網友回復:
你可以使用 awk。如果檔案名是 test.txt 那么
awk '{print $1}' ORS=',' test.txt | awk '{print substr($1, 1, length($1)-1)}'
第一個 awk 命令用逗號 (test1,test2,test3,) 連接三行。第二個 awk 命令只是從字串中洗掉最后一個逗號。
uj5u.com熱心網友回復:
使用工具“tr”(翻譯)和 sed 洗掉最后一個逗號:
tr '\n' , < "$source_file" | sed 's/,$//'
如果要將輸出保存到變數中:
var="$( tr '\n' , < "$source_file" | sed 's/,$//' )"
uj5u.com熱心網友回復:
使用 sed:
$ sed ':a;N;$!ba;s/\n/,/g' file
輸出:
test1,test2,test3
我想這是我最初撿到它的地方。
uj5u.com熱心網友回復:
另一個無環純 Bash 解決方案:
contents=$(< input.txt)
printf '%s\n' "${contents//$'\n'/,}"
contents=$(< input.txt)相當于contents=$(cat input.txt)。它將input.txt檔案的內容(自動洗掉尾隨換行符)放入變數contents."${contents//$'\n'/,}"用逗號字符替換所有出現的換行符 ($'\n')contents。請參閱引數擴展 [Bash Hackers Wiki]。- 請參閱為什么 printf 比 echo 好?用于解釋為什么
printf '%s\n'使用而不是echo.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/368548.html
上一篇:如何通過Shell腳本更改用戶名
