如果我有
这样的文字/mnt/data/web/web content/page 1/home page.txt
我使用以下命令获取我的文本,然后将其传送到另一个命令。
cat somefile.txt | awk '{$1=$2=$3=$4=$5=$6=$7=$8=$9=$10=""; print $0}'
我需要将上面的命令传递给另一个命令以添加反斜杠
如何在每个空格之前添加反斜杠,以便我得到正确的* nix路径
即
/mnt/data/web/web\ content/page\ 1/home\ page.txt
理论上文本可以无限长,但我总是需要在每个空格之前使用反斜杠。 最终脚本将用于freebsd&的Linux
谢谢!
答案 0 :(得分:6)
此awk
应该:
awk '{gsub(/ /,"\\ ")}8' file
/mnt/data/web/web\ content/page\ 1/home\ page.txt
答案 1 :(得分:2)
对你有用吗?
echo "/mnt/data/web/web content/page 1/home page.txt" > input.txt
然后:
sed 's/ \+/\\ /g' input.txt > output.txt
然后:
cat output.txt
/mnt/data/web/web\ content/page\ 1/home\ page.txt
如果您想为所有空间执行此操作,可以尝试awk
awk
:
awk -F" " '{ print $1"\\ " $2"\\ " $3"\\ " $4}' input.txt > output.txt
答案 2 :(得分:1)
这可能适合你(GNU sed):
sed 's/\s/\\&/g' file
答案 3 :(得分:0)
您需要引用整个路径:
# Create file
echo Hi > "a file with spaces"
# Try to cat it
n="a file with spaces"
cat $n
cat: a: No such file or directory
cat: file: No such file or directory
cat: with: No such file or directory
cat: spaces: No such file or directory
# With quotes this time :-)
cat "$n"
Hi
答案 4 :(得分:0)
# Wrap file path with "" so it can be treated as $1
# Wrap command with "" if spaces are present to treat as $2
# Wraping time only nessisay for pros ;-) $3
# Example synax;
# format_space_do_time "/dir with/sp ac e s" "Comand With options" "TimeToSleep"
# Set $1, $2 and $3 variable names such that they can be hard-coded for debugging
File_Path="$1"
Commands="$2"
Timed_Sleep="$3"
format_space_do_time (){
# Check if services or command is already in proggress
while true
do
if ps ax | grep -v grep | grep "$Commands" > /dev/null
then
# Waite $Time_Sleep for $Commands to finish
sleep $Time_Sleep;
else
# $Commands not detected. Start'em now
for i in "$File_Path/"*
do
# Magic time, lets deal with spaces in $i and save it to $entry
# Option 1 replaces " " with "$'\0'" which is bashs way of dealing with spaces
entry1=$(echo "$i" | sed 's/ /$\'\\\0\'/g')
# Option 2 can be used to replace " " with "\ " of cource without the quotes around them :-)
entry2=$(echo "$i" | sed 's/ /\\\ /g')
# Clear previous outputs
clear
# run $Commands against $entry1
# Change 1 to 2 for the other option
${Commands} "${entry1}" > /dev/null
done
fi
done
}
以上链接
中添加了上述scirpthttp://www.cenolan.com/2013/03/looping-video-playlist-omxplayer-raspberry-pi/
他们有一些工作正常,直到我不得不处理Gatesbox用户的硬盘驱动器。我个人使用这个脚本通过命令行播放音乐和电影。例如,我将上面保存为omx_play_lister.sh然后保存chmod +x omx_play_lister
并运行;
./omx_play_lister "/media/mount/cWin/Music by artist/artist name and album folder" "omxplayer -ohdmi --vol=-2500" "5"
哪位乐意接受文件路径; /media/mount/cWin/Music by artist/artist name and album folder
并转换为/media/mount/cWin/Music\ by\ artist/artist\ name\ and\ album\ folder
或在omxplayer和ls以及许多其他不太喜欢""传递文件路径时的东西。在接近结尾的范围内使用sed命令的好处是,即使文件本身包含空格,在传递给$Commands
之前也会格式化这些空格。
小"${entry}"
和"$File_Path/"*
,其中最棘手的格式化排序,但它适用于我所需要的东西以及可能有一些moddification也适用于您的用法。
快乐的黑客攻击和修改。