我有一个我需要在bash脚本中使用的CSV文件。 CSV的格式如下。
server1,file.name
server1,otherfile.name
server2,file.name
server3,file.name
我需要能够将此信息提取到数组或其他方式,以便我可以过滤信息,只为单个服务器提取数据,然后我可以将其传递给脚本中的另一个命令。
我需要这样做。
Import workfile.csv
check hostname | return only lines from workfile.csv that have the hostname as column one and store column 2 as a variable.
find / -xdev -type f -perm -002 | compare to stored info | chmod o-w all files not in listing
由于我正在工作的环境,我因使用bash而陷入困境。
答案 0 :(得分:0)
csv可以很大,可以在查找参数列表中添加所有文件名。 您也不希望在循环中为csv中的每一行调用find。
解决方案:
首先在tmp文件中创建一个完整的文件列表
第二个解析csv并过滤文件
第三是chmod -w。
下一个解决方案将文件存储在tmp中 创建一个将servername作为参数的脚本。 请参阅代码中的注释:
# Before EDIT:
# Hostname by parameter 1
# Check that you have a hostname
if [ $# -ne 1 ]; then
echo "Usage: $0 hostname"
# Exit script, failure
exit 1
fi
hostname=$1
# Edit, get hostname by system call
hostname=$(hostname)
# Or: hostname=$(hostname -s)
# Additional check
if [ ! -f workfile.csv ]; then
echo "inputfile missing"
exit 1
fi
# After edits, ${hostname} is now filled.
find / -xdev -type f -perm -002 -name "${file}" > /tmp/allfiles.tmp
# Do not use cat workfile.csv | grep ..., you do not need to call cat
# grep with ^ for beginning of line, add a , for a complete first field
# grep "^${hostname}," workfile.csv
# cut for selecting second field with delimiter ','
# cut -d"," -f2
# while read file => can be improved with xargs but lets start with this.
grep "^${hostname}," workfile.csv | cut -d"," -f2 | while read file; do
# Using sed with #, not /, since you need / in the search string
# Variable in sed mist be outside the single quotes and in double quotes
# Add $ after the file for end-of-line
# delete the line with the file (#searchstring#d)
sed -i '#/'"${file}"'$#d' /tmp/allfiles.tmp
done
echo "Review /tmp/allfiles.tmp before chmodding all these files"
echo "Delete the echo and exit when you are happy"
# Just an exit for testing
exit
# Using < is for avoiding a call to cat
</tmp/allfiles.tmp xargs chmod -w
当您可以chmod -w所有文件并chmod + w csv中的文件时,可能会更容易。这与你提出的情况略有不同,因为来自csv的所有文件在此过程之后都是可写的,也许你不希望这样。