ede*_*esz 15 command-line bash paths text-processing
我在 bash 变量中有一个 Windows 路径作为字符串:
file='C:\Users\abcd\Downloads\testingFile.log'
Run Code Online (Sandbox Code Playgroud)
我正在尝试将此路径转换为以/c/Users....
我的尝试
以下工作:
file=${file/C://c}
file=${file//\\//}
echo $file
> /c/Users/abcd/Downloads/testingFile.log
Run Code Online (Sandbox Code Playgroud)
问题
在这里,我为包含文件路径的字符串执行了此操作。我问这个问题的原因是我必须在 Ubuntu 16.04 的 bash 脚本中转换 20 个这样的字符串,每次我这样做时,我必须为每次转换写 2 行 - 它占用了大量空间!
题
有没有办法组合这两个命令
file=${file/C://c}
file=${file//\\//}
Run Code Online (Sandbox Code Playgroud)
成一个命令?
wja*_*rea 19
有一种方法可以使用 一次进行两种替换sed,但这不是必需的。
这是我解决这个问题的方法:
filenames=(
'C:\Users\abcd\Downloads\testingFile.log'
# ... add more here ...
)
for f in "${filenames[@]}"; do
f="${f/C://c}"
f="${f//\\//}"
echo "$f"
done
Run Code Online (Sandbox Code Playgroud)
如果要将输出放入数组而不是打印,请用echo赋值替换该行:
filenames_out+=( "$f" )
Run Code Online (Sandbox Code Playgroud)
ste*_*ver 10
如果这是你想做很多次的事情,那为什么不创建一个小shell函数呢?
win2lin () { f="${1/C://c}"; printf '%s\n' "${f//\\//}"; }
$ file='C:\Users\abcd\Downloads\testingFile.log'
$ win2lin "$file"
/c/Users/abcd/Downloads/testingFile.log
$
$ file='C:\Users\pqrs\Documents\foobar'
$ win2lin "$file"
/c/Users/pqrs/Documents/foobar
Run Code Online (Sandbox Code Playgroud)