shell中 cut -d'/' -f1 是什么意思
时间: 2023-11-27 19:49:08 浏览: 32
这个命令的意思是将输入的文本按照"/"进行分割,并取出分割后的第1个字段。具体解释如下:
- `cut` 命令用于剪切文本中的列。
- `-d` 参数指定分割符为"/"。
- `-f` 参数指定要剪切的字段,这里是第1个字段。
举个例子,假设有以下文本:
```
/home/user/docs/file.txt
```
执行 `cut -d'/' -f1` 命令后,输出结果为:
```
home
```
因为它将输入的文本按照"/"进行分割,然后取出了分割后的第1个字段。
相关问题
dumpsys window | awk '/mCurrentFocus/ {print $NF}' | cut -d/ -f1 | sed 's/[{}]//g' mCurrentFocus=null com.rxgb.launcher
如果输出结果中包含了 `mCurrentFocus=null`,那么说明当前屏幕上没有任何应用程序处于前台运行状态。在这种情况下,你可以使用条件语句来判断输出结果是否包含应用程序包名,如果包含则输出应用程序包名,否则输出提示信息。
具体示例代码如下:
```python
import re
import subprocess
output = subprocess.check_output("dumpsys window windows", shell=True).decode()
match = re.search(r"mCurrentFocus=(Window\{.+?\})", output)
if match:
package_name = match.group(1).split("/")[-1].split()[0].replace("{", "").replace("}", "")
print("Package Name:", package_name)
else:
print("No application is currently in the foreground.")
```
这个代码中先使用正则表达式来匹配 `mCurrentFocus` 的值,如果匹配到了就输出应用程序包名,否则输出提示信息。注意,这里使用了 `split()` 方法来进一步从匹配到的字符串中提取应用程序包名。
输出结果类似于:
```
Package Name: com.rxgb.launcher.activity.MainActivity
```
或者:
```
No application is currently in the foreground.
```
这样就可以避免在没有应用程序处于前台运行时输出错误信息了。
#!/system/bin/sh # 获取当前活跃窗口 get_display_id() { local focus=$(dumpsys window | grep "mCurrentFocus" | tail -n 1 | awk '{print $NF}' | cut -d'}' -f1) local displays=$(dumpsys window | grep display | grep 'imeInputTarget') local activity=$(echo "$displays" | grep "$focus" | cut -d'#' -f2 | awk '{print $NF}' | cut -d'}' -f1) focus是否和activity一样可以返回一个布尔类型 } get_display_id_activity() { local displays=$(dumpsys window | grep display | grep 'imeInputTarget') dumpsys window | grep display | grep 'imeInputTarget' | awk '{print $4,$7}' | cut -d'}' -f1 local display_id=$(echo "$displays" | cut -d'#' -f2 | awk '{print $1}') local activity=$(echo "$displays" | cut -d'#' -f2 | awk '{print $NF}' | cut -d'}' -f1) echo $display_id $activity } get_display_id_activity # 判断窗口所在的显示器 display_id=$(get_display_id) case esac 优化一下
可以将 `get_display_id_activity()` 函数中的冗余代码去掉,同时在 `case` 语句中添加具体的操作。代码优化后如下所示:
```shell
#!/system/bin/sh
# 获取当前活跃窗口的显示器 ID 和活动
get_display_id_activity() {
local displays=$(dumpsys window | grep display | grep 'imeInputTarget')
local display_id=$(echo "$displays" | cut -d'#' -f2 | awk '{print $1}')
local activity=$(echo "$displays" | cut -d'#' -f2 | awk '{print $NF}' | cut -d'}' -f1)
echo "$display_id $activity"
}
# 获取当前活跃窗口所在的显示器 ID
get_display_id() {
local focus=$(dumpsys window | grep "mCurrentFocus" | tail -n 1 | awk '{print $NF}' | cut -d'}' -f1)
local displays=$(dumpsys window | grep display | grep 'imeInputTarget')
local activity=$(echo "$displays" | grep "$focus" | cut -d'#' -f2 | awk '{print $NF}' | cut -d'}' -f1)
echo "$activity"
}
# 获取当前活跃窗口所在的显示器 ID,然后根据不同的显示器 ID 执行不同的操作
display_id=$(get_display_id)
case "$display_id" in
"display_id_1")
# 执行显示器1的操作
;;
"display_id_2")
# 执行显示器2的操作
;;
*)
# 默认操作
;;
esac
```
这样代码更加简洁,可读性也更好了。