string splitting

假设我们要split以':'分隔的PATH变量,并迭代每个PATH中的目录。我们可以使用tr把':'转换成空格,之后直接迭代这个变量?

for d in $ ( echo $PATH | tr ':' ' ' ); do
    echo $d
done

这段代码在有时候正常工作,有时候不行。假设PATH中的的目录不含有空格,则会正常工作。

由于command substitution结束后,shell会进行word splitting,根据IFS的值,分割成不同的word。默认IFS=<space><tab><newline>。而在这里我们假设PATH=/usr/bin:/user/local/bin:/home/arum/foo bar,而上述代码的输出将是:

/usr/bin
/usr/local/bin
/home/arum/foo
bar

我们原本是想直接迭代/home/arum/foo bar的目录,但是由于foo bar之间的空格是IFS的一部分,所以导致在word splitting过程中,被分成了2个部分。我们可以使用另一种方法,这种方法通过修改IFS来达到目的。

# save IFS
OLD_IFS= $IFS
IFS= ':'

for d in $PATH; do
    echo $d
done

# restore IFS
IFS= $OLD_IFS

这段代码的输出就正确了。

我们还可以将分隔的结果保存到一个数组当中,以供以后使用。

a = ( $PATH )
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
In Visual Studio Code (VS Code), working with strings involves various operations such as creating, manipulating, and displaying strings. Here are a few common string-related tasks you can perform in VS Code: 1. Declaring and Initializing Strings: In most programming languages, including C++, C#, Python, and JavaScript, you can declare and initialize a string variable using quotation marks. For example: ```python str = "Hello, World!" ``` 2. Concatenating Strings: You can concatenate or combine multiple strings together using the concatenation operator (`+`). For instance: ```python str1 = "Hello" str2 = "World" result = str1 + " " + str2 print(result) # Output: Hello World ``` 3. String Length: To determine the length of a string, you can use the `len()` function or the `length` property. Here's an example: ```python str = "Hello, World!" length = len(str) print(length) # Output: 13 ``` 4. Accessing Characters in a String: You can access individual characters within a string using indexing. In most programming languages, indexing starts from 0. For example: ```python str = "Hello" first_char = str[0] # Accessing the first character print(first_char) # Output: H ``` 5. String Manipulation: VS Code provides various built-in functions or methods to manipulate strings, such as converting case (uppercase/lowercase), replacing substrings, splitting strings into substrings, and more. These are just a few examples of working with strings in VS Code. The specific syntax and available string operations may vary depending on the programming language you are using.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值