如何指定换行符分隔的字符串,例如三行到三个变量?
class MyBasePopUp: UIViewController, UIGestureRecognizerDelegate {
var tap: UITapGestureRecognizer!
override func viewDidAppear(_ animated: Bool) {
tap = UITapGestureRecognizer(target: self, action: #selector(onTap(sender:)))
tap.numberOfTapsRequired = 1
tap.numberOfTouchesRequired = 1
tap.cancelsTouchesInView = false
tap.delegate = self
self.view.window?.addGestureRecognizer(tap)
}
internal func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
internal func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
let location = touch.location(in: self.view)
if self.view.point(inside: location, with: nil) {
return false
}
else {
return true
}
}
@objc private func onTap(sender: UITapGestureRecognizer) {
self.view.window?.removeGestureRecognizer(sender)
self.dismiss(animated: true, completion: nil)
}
我也尝试使用# test string
s='line 01
line 02
line 03'
# this doesn't seem to make any difference at all
IFS=$'\n'
# first naive attempt
read a b c <<< "${s}"
# this prints 'line 01||':
# everything after the first newline is dropped
echo "${a}|${b}|${c}"
# second attempt, remove quotes
read a b c <<< ${s}
# this prints 'line 01 line 02 line 03||':
# everything is assigned to the first variable
echo "${a}|${b}|${c}"
# third attempt, add -r
read -r a b c <<< ${s}
# this prints 'line 01 line 02 line 03||':
# -r switch doesn't seem to make a difference
echo "${a}|${b}|${c}"
# fourth attempt, re-add quotes
read -r a b c <<< "${s}"
# this prints 'line 01||':
# -r switch doesn't seem to make a difference
echo "${a}|${b}|${c}"
代替echo ${s} | read a b c
,但无法使用它。
这可以用bash完成吗?
答案 0 :(得分:2)
读取默认输入分隔符是\ n
{ read a; read b; read c;} <<< "${s}"
-d char:允许指定另一个输入分隔符
例如,输入字符串
中没有字符SOH(1 ASCII)IFS=$'\n' read -r -d$'\1' a b c <<< "${s}"
编辑:-d可以采用空参数,空格在-d和null参数之间是必需的:
IFS=$'\n' read -r -d '' a b c <<< "${s}"
编辑:在评论任意行数的解决方案之后
function read_n {
local i s n line
n=$1
s=$2
arr=()
for ((i=0;i<n;i+=1)); do
IFS= read -r line
arr[i]=$line
done <<< "${s}"
}
nl=$'\n'
read_n 10 "a${nl}b${nl}c${nl}d${nl}e${nl}f${nl}g${nl}h${nl}i${nl}j${nl}k${nl}l"
printf "'%s'\n" "${arr[@]}"
答案 1 :(得分:2)
您正在寻找readarray
命令,而不是read
。
readarray -t lines <<< "$s"
(从理论上讲,这里不需要引用$s
。除非您使用的是bash
4.4或更高版本,否则我会引用它,因为先前版本的{{1}中存在一些错误}。)
一旦线条在数组中,您可以根据需要分配单独的变量
bash