[英]How to read in a line in a bash script using IFS and while the line is being read create a new line between a specified charater
我正在嘗試創建一個bash腳本,該腳本將讀取具有一行的文件,並且在讀取該行並遇到空白時,創建一個新行,然后繼續讀取該行
試圖讀取的文件
david:69 jim:98 peter:21 sam:56 april:32
這是我目前的bash腳本
#!/bin/bash
fileName=$1 # storing the file
numberSpaces=$2 # will be used later to specify the number of spaces inbetween name:score
# Checking if no file was specified on the command line
[ $# -eq 0 ] && { echo "No file specified"; exit 1;}
# Checking if the file entered on the command line exists
[ ! -f $fileName ] && { echo "File $fileName not found."; exit 2;}
# Internal Field Seperator(IFS) will read what is on the left and right of a specified char
while IFS=' ' read -r name;
do
echo "$name"
echo -e "\n"
done < $fileName
#while read -r line
#do
# name="$line"
# echo "Content of file - $name"
#done < "$fileName"
我正在嘗試將其打印到屏幕上
$ spacing.sh file.txt
$ david:69
$ jim:98
$ peter:21
$ sam:56
$ april:32
當前它僅將文件內容打印在一行上。 任何幫助或建議,將不勝感激
一行:
tr -s " " "\n" < file.txt
您將需要在read
使用-d
選項以使其一直讀取到給定的定界符為止:
while IFS= read -r -d ' ' name;
do
echo "$name"
done < <(sed 's/$/ /' file.txt)
根據help read
:
-d delim: continue until the first character of DELIM is read, rather than newline
sed
用於插入行尾的空格,以便-d
可以將空格用作分隔符,
您可以將行拆分成一個數組,然后遍歷該數組。
read -r -a fields < "$fileName"
for field in "${fields[@]}"; do
echo "$field"
done
此處無需設置IFS
的值,因為默認值(空格,制表符,換行符)足以分割由任意空格分隔的行。 使用IFS
一個示例是隨后將每個字段的以冒號分隔的部分分成兩個單獨的變量:
IFS=: read -r name count <<< "$field" # field=david:69
# name=david
# count=69
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.